package model

import (
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/shopspring/decimal"
	"time"
)

// 签到活动配置
func PromoTreasureConfigList() ([]PromoTreasureConfig, error) {

	var data []PromoTreasureConfig
	query, _, _ := dialect.From("tbl_promo_treasure_config").
		Select(colsPromoTreasureConfig...).Where(g.Ex{}).Order(g.C("invite_num").Asc()).ToSQL()
	err := meta.SlaveDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	return data, nil
}

// 签到记录
func PromoTreasureMemberRecord(uid string) ([]PromoTreasureRecord, error) {

	var data []PromoTreasureRecord
	query, _, _ := dialect.From("tbl_promo_treasure_record").
		Select(colsPromoTreasureRecord...).Where(g.Ex{"uid": uid}).ToSQL()
	err := meta.SlaveDB.Select(&data, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	return data, nil
}

// 签到记录
func PromoTreasureApply(uid string, inviteNum int) error {

	data := PromoTreasureConfig{}
	query, _, _ := dialect.From("tbl_promo_treasure_config").
		Select(colsPromoTreasureConfig...).Where(g.Ex{"invite_num": inviteNum}).ToSQL()
	err := meta.MerchantDB.Get(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	if err == sql.ErrNoRows {
		return errors.New(helper.ParamErr)
	}

	ts := time.Now()
	// 增加会员余额
	amount, _ := decimal.NewFromString(data.Amount)
	treasureRecord := PromoTreasureRecord{
		ID:        helper.GenId(),
		UID:       uid,
		Username:  myUserHelp.GetMemberName(uid),
		InviteNum: inviteNum,
		Amount:    amount.String(),
		CreatedAt: ts.Unix(),
	}

	fAmount, _ := amount.Float64()
	myUserHelp.AddBalanceTransactionRecord(uid, fAmount, helper.TransactionTreasureDividend, "0", helper.GenId(), 0.00, "", "", 0)
	myUserHelp.AddUserBalanceByDecimal(uid, amount.Abs())
	query, _, _ = dialect.Insert("tbl_promo_treasure_record").Rows(treasureRecord).ToSQL()
	myredis.AddLogToRedis(query)

	return nil
}
